<!-- 游戏RTP调控 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="0" @changeSize="changeSize" :showFrom="false" :showSet="false"
    @changePage="changePage" @search="getSearchList" @reset="resetDetails" @changeTh="data.dialogVisible = true">
    <template #form></template>
    <template #button>
      <el-button type="danger" size="small" @click="initialSynchronization()">
        {{ t('958') }}
      </el-button>
      <div class="tipsTextRed marginL10 marginT5">
        <p>{{ t('983') }}</p>
        <p>{{ t('984') }}</p>
        <p>{{ t('985') }}</p>
      </div>
    </template>
    <template #table>
      <el-table-column :label="t('1021')">
        <template v-for="(item, index) in data.fieldsFosterer" :key="index">
          <el-table-column :prop="item.prop" :label="item.label" :width="item.width" show-overflow-tooltip>
            <template #header>
              <el-tooltip v-if="item.tips" effect="dark" placement="top">
                <template #content>
                  {{ item.tips }}
                </template>
                <el-icon class="ques-tips">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              {{ item.label }}
            </template>
            <template v-if="item.prop == 'player_state'" #default="scope">
              <el-tag type="success">{{ t('992') }}</el-tag>
            </template>
            <template v-if="item.prop == 'a_slots_pigNUmber'" #default="scope">
              {{ selectToLabel(data.cycleList, Number(scope.row.a_slots_pigCycle)) + scope.row.a_slots_pigNUmber }}次
            </template>
          </el-table-column>
        </template>
      </el-table-column>
      <el-table-column :label="t('1022')">
        <template v-for="(item, index) in data.fieldsProtection" :key="index">
          <el-table-column :prop="item.prop" :label="item.label" :width="item.width" show-overflow-tooltip>
            <template #header>
              <el-tooltip v-if="item.tips" effect="dark" placement="top">
                <template #content>
                  {{ item.tips }}
                </template>
                <el-icon class="ques-tips">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              {{ item.label }}
            </template>
            <template v-if="item.prop == 'a_slots_protectopen'" #default="scope">
              <el-tag :type="scope.row.a_slots_protectopen ? 'success' : 'danger'">
                {{ selectToLabel(DEMOPLAY, scope.row.a_slots_protectopen) }}</el-tag>
            </template>
            <template v-if="item.prop == 'lower'" #default="scope">
              <span v-if="scope.row.lowerMin && scope.row.lowerMax">{{ scope.row.lowerMin + '%' + '~' + scope.row.lowerMax + '%'
                }}</span>
              <span v-else> - </span>
            </template>
            <template v-if="item.prop == 'upper'" #default="scope">
              <span v-if="scope.row.upperMin && scope.row.upperMax">{{ scope.row.upperMin + '%' + '~ '+scope.row.upperMax+'%' }}</span>
              <span v-else> - </span>
            </template>
            <template v-if="item.prop == 'beginner'" #default="scope">
              {{ scope.row.beginner }}%
            </template>
            <template v-if="item.prop == 'nobeginner'" #default="scope">
              {{ scope.row.nobeginner }}%
            </template>
          </el-table-column>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="t('97')" width="90" align="center">
        <template #header>
          <el-tooltip effect="dark" :content="t('574')" placement="top">
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          {{ t('98') }}
        </template>
        <template #default="scope">
          <el-button type="warning" size="small" @click="checkDetails(scope.row)">
            {{ t('98') }}
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData"></tableHeader>

  <!-- 调控配置 -->
  <!-- <RtpControl :show="data.isShowDetails" :checkedItem="data.checkedItem" @onHideDetails="onHideDetails"/> -->
  <el-dialog v-model="data.isShowDetails" :title="t('964')" :close-on-click-modal="false" :close-on-press-escape="false"
    width="50%" top="25vh" @close="data.isShowDetails = false">
    <div class="dialogMaxHeight">
      <el-form ref="ruleFormRef" :model="data.formParams" :inline="true" :rules="data.rules" :scroll-to-error="true">
        <form-item :title="t('944')" :pass="true" value="rtp_num">
          <el-input-number class="width180" v-model="data.formParams.rtp_num" :min="0" :max="99999999999999999999"
            :precision="0" :placeholder="t('944')" clearable controls-position="right" />
          <span class="tipsText">({{ t('945') }})</span>
        </form-item>
        <form-item :title="t('950')" :pass="true" value="beginner">
          <el-input-number class="width180" v-model="data.formParams.beginner" :min="0" :max="100" :precision="0"
            :placeholder="t('950')" clearable controls-position="right" />%
          <span class="tipsText">({{ t('951') }})</span>
        </form-item>
        <form-item :title="t('952')" :pass="true" value="nobeginner">
          <el-input-number class="width180" v-model="data.formParams.nobeginner" :min="0" :max="100" :precision="0"
            :placeholder="t('952')" clearable controls-position="right" />%
          <span class="tipsText">({{ t('953') }})</span>
        </form-item>
        <form-item :title="t('1010')" value="a_slots_pig">
          <div class="marginB5">
            {{ t('1011') }}：<el-input-number v-model="data.formParams.a_slots_pigProfit" :min="1" :max="999999999999999999"
              :precision="0" :placeholder="t('1011')" clearable controls-position="right" />
            <span class="tipsText">({{ t('1012') }})</span>
          </div>
          <div class="marginB5">
            {{ t('1013') }}：<el-input-number v-model="data.formParams.a_slots_pigWater" :min="1" :max="999999999999999999"
              :precision="0" :placeholder="t('1013')" clearable controls-position="right" />
            <span class="tipsText">({{ t('1014') }})</span>
          </div>
          <div class="marginB5">
            {{ t('1015') }}：<el-select v-model="data.formParams.a_slots_pigCycle" :placeholder="t('340')" filterable
              @change="chooseCycle">
              <el-option v-for="item in data.cycleList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            {{ t('1016') }}：<el-input-number v-model="data.formParams.a_slots_pigNUmber" :min="1" :max="999999999999999999"
              :precision="0" :placeholder="t('1016')" clearable controls-position="right" />
            <span class="tipsText">({{ t('1017') }})</span>
            <div v-if="data.formParams.a_slots_pigCycle == 5 ? true : false">
              {{ t('1018') }}：<el-date-picker v-model="data.formParams.date" type="datetimerange" range-separator="-"
                :start-placeholder="t('26')" :end-placeholder="t('26')" value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="indexStore.disabledBeforeDateTime" />
            </div>
          </div>
          <div class="marginB5">
            {{ t('1019') }}：<el-input-number v-model="data.formParams.a_slots_pigInning" :min="1" :max="999999999999999999"
              :precision="0" :placeholder="t('1019')" clearable controls-position="right" />
            <span class="tipsText">({{ t('1020') }})</span>
          </div>
        </form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="data.isShowDetails = false">{{ t('240') }}</el-button>
        <el-button type="primary" @click="editControl">{{ t('241') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import FormItem from '@/components/FormItem/FormItem.vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import { DEMOPLAY } from '@/config/eunm'
import { Time } from '@/utils/serverTime'
import { setTimestampTime } from '@/utils/time'
import { selectToLabel, setCommaToArr, setSemicolonToArr, setArrStr } from '@/utils/index'
import { BigHundred, BigTimeHundred } from '@/utils/math'
import { getRTP, editRTP } from '@/api/game'
import { editRtpSwitch } from '@/api/settion'

import { useStore } from '@/stores/index'
const indexStore = useStore()
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const data = reactive({
  type: 1,
  query: {
    page: 1,
    size: 50,
  },
  list: [],
  total: 0,
  fields: [

  ],
  fieldsFosterer: [
    { label: t('997'), prop: 'player_state', width: '155', tips: t('998') },
    { label: t('999'), prop: 'a_slots_pigProfit', width: '120', tips: t('1000') },
    { label: t('1001'), prop: 'a_slots_pigWater', width: '120', tips: t('1002') },
    { label: t('1003'), prop: 'a_slots_pigNUmber', width: '150', tips: t('1004') },
    { label: t('1005'), prop: 'a_slots_pigInning', width: '150', tips: t('1006') },
  ],
  fieldsProtection: [
    { label: t('954'), prop: 'a_slots_protectopen', width: '120', tips: t('954') },
    { label: t('944'), prop: 'rtp_num', width: '120', tips: t('945') },
    { label: t('938'), prop: 'gear', width: '120', tips: t('939') },
    { label: t('946'), prop: 'lower', width: '', tips: t('947') },
    { label: t('948'), prop: 'upper', width: '', tips: t('949') },
    { label: t('950'), prop: 'beginner', width: '', tips: t('951') },
    { label: t('952'), prop: 'nobeginner', width: '', tips: t('953') },
  ],
  dialogVisible: false,
  checkedItem: {} as any,
  isShowDetails: false,
  commercialForm: {
    operated_id: -1,
    agent_ids: [],
    game_ids: [],
    column_value: '0',
    column: 'a_rtp_control'
  },
  commercialArray: [] as any[],
  whiteList: [] as any[],
  controlList: [] as any[],
  formParams: {
    rtp_num: 0,
    beginner: 0,
    nobeginner: 0,
    a_slots_pigProfit: 0,
    a_slots_pigWater: 0,
    a_slots_pigNUmber: 1,
    a_slots_pigCycle: 0,
    pigCycle: 0,
    a_slots_pigInning: 0,
    date:[]
  } as any,
  rules: {
    rtp_num: [{ required: true, message: t('19') + t('944'), trigger: 'blur' }],
    beginner: [{ required: true, message: t('19') + t('950'), trigger: 'blur' }],
    nobeginner: [{ required: true, message: t('19') + t('952'), trigger: 'blur' }],
  },
  cycleList: [
    { label: t('993'), value: 1 },
    { label: t('994'), value: 2 },
    { label: t('995'), value: 3 },
    { label: t('996'), value: 4 },
    { label: t('1009'), value: 5 },
  ]
})

onMounted(async () => {
  getSearchList()
})

const getSearchList = async () => {
  let query = JSON.parse(JSON.stringify(data.query));
  indexStore.setPageLoading(true)
  let res = await getRTP(query)
  res.data?.list?.forEach((item: any) => {
    item.a_slots_protect_arr.forEach((second: any, index: number) => {
      // 新手局数
      if (index == 0) item.rtp_num = Number(second)
      // 新手救助次数
      if (index == 1) item.beginner = Number(setCommaToArr(second)[0])
      // 非新手救助次数
      if (index == 1) item.nobeginner = Number(setCommaToArr(second)[1])
      // 检测执行局数
      if (index == 2) item.rtp_check = second
      // 浮动率
      if (index == 3) item.rtp_radio = second
      // 保护配置
      if (index == 4) item.rtp_control = setArrControl(second, item.lower_max, item.lower_min, item.upper_max, item.upper_min, item.rtp_num, item.a_slots_protectopen, item.a_slots_pig)
    })
  })
  indexStore.setPageLoading(false)
  data.checkedItem = res.data.list[0]
  data.list = res.data.list[0].rtp_control
  data.controlList = res.data.list[0].a_slots_protect_arr
}

// 选择触发周期
const chooseCycle = async (value: any) => {
  if (data.formParams.pigCycle > value) {
    ElMessageBox.confirm(t('1008'), t('650'), {
      confirmButtonText: t('241'),
      cancelButtonText: t('240')
    }).then(async () => {

    }).catch(() => {
      data.formParams.a_slots_pigCycle = data.formParams.pigCycle
    })
  }
}

// 详情
const checkDetails = async (row: any) => {
  // 处理弹窗数据
  data.formParams = JSON.parse(JSON.stringify(row))
  data.isShowDetails = true
}

// 修改保护配置
const editControl = async () => {
  const parameter = JSON.parse(JSON.stringify(data.formParams)), arr = JSON.parse(JSON.stringify(data.list));
  arr.forEach((item: any) => {
    if (item.gear == parameter.gear) {
      item.beginner = parameter.beginner
      item.nobeginner = parameter.nobeginner
    }
  })
  if(!parameter.a_slots_pigProfit || !parameter.a_slots_pigWater || !parameter.a_slots_pigNUmber || !parameter.a_slots_pigInning) return ElMessage.error(t('1023'))
  // 保护配置
  let protect = parameter.rtp_num + '|' + parameter.beginner + ',' + parameter.nobeginner + '|' + data.controlList[2] + '|' + data.controlList[3] + '|' + setStrControl(arr)
  // 养客机制配置
  let a_slots_pig = parameter.a_slots_pigCycle+','+parameter.a_slots_pigWater+','+parameter.a_slots_pigProfit+','+parameter.a_slots_pigNUmber+','+parameter.a_slots_pigInning;
  if (parameter.a_slots_pigCycle == 5) {
    parameter.time = new Time(parameter.date[0]).toTimestamp() + ',' + new Time(parameter.date[1]).toTimestamp()
    a_slots_pig = a_slots_pig + ',' + parameter.time
  }
  await editRTP({
    agent_id: data.checkedItem.agent_id,
    a_slots_protect: protect,
    a_slots_protectopen: data.checkedItem.a_slots_protectopen,
    a_slots_pig: a_slots_pig
  })
  ElMessage.success(t('342'))
  onHideDetails(true)
}

// 功能开关控制
const initialSynchronization = async () => {
  const parameter = JSON.parse(JSON.stringify(data.checkedItem))
  let message = `${(parameter.a_slots_protectopen == 0 ? t('101') : t('102')) + t('719')}？`;
  ElMessageBox.confirm(message, t('650'), {
    confirmButtonText: t('241'),
    cancelButtonText: t('240')
  }).then(async () => {
    await editRtpSwitch({
      agent_ids: [data.checkedItem.agent_id],
      a_slots_protectopen: parameter.a_slots_protectopen ? 0 : 1
    })
    ElMessage.success(t('342'))
    onHideDetails(true)
  }).catch(() => { })
}

// 调控配置
const setArrControl = (str: string, lowerMax: any, lowerMin: any, upperMax: any, upperMin: any, num: number, protectopen: number, pig: string) => {
  let arr = [], newArr: any[] = [], slotsPig = setCommaToArr(pig);
  arr = setSemicolonToArr(str)
  arr?.forEach((item: any, index: number) => {
    if (Number(slotsPig[3]) == 5) {
      item.date = [setTimestampTime(Number(slotsPig[5])), setTimestampTime(Number(slotsPig[6]))]
    } else {
      item.date = []
    }
    newArr.push({
      gear: Number(item[0]),
      drop: Number(item[1]),
      pull: Number(item[2]),
      beginner: BigHundred(item[3]),
      nobeginner: BigHundred(item[4]),
      lowerMax: BigHundred(lowerMax[index] ? lowerMax[index] : 0),
      lowerMin: BigHundred(lowerMin[index] ? lowerMin[index] : 0),
      upperMax: BigHundred(upperMax[index] ? upperMax[index] : 0),
      upperMin: BigHundred(upperMin[index] ? upperMin[index] : 0),
      rtp_num: num,
      a_slots_protectopen: protectopen,
      a_slots_pigCycle: Number(slotsPig[0]), // 周期
      pigCycle: Number(slotsPig[0]), // 周期
      a_slots_pigWater: Number(slotsPig[1]), //流水倍数
      a_slots_pigProfit: Number(slotsPig[2]), //玩家净盈利
      a_slots_pigNUmber: Number(slotsPig[3]), //生效次数
      a_slots_pigInning: Number(slotsPig[4]), //局数CD
      date: item.date
    })
  })
  return newArr
}
const setStrControl = (arr: any) => {
  let newArr = [] as any[];
  arr?.forEach((item: any) => {
    item.beginner = BigTimeHundred(item.beginner)
    item.nobeginner = BigTimeHundred(item.nobeginner)
    newArr.push({
      gear: item.gear,
      drop: item.drop,
      pull: item.pull,
      beginner: item.beginner,
      nobeginner: item.nobeginner
    })
  })
  return setArrStr(newArr)
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}
const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const BatchControlRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.dialogVisible = false
  data.isShowDetails = false
  if (data.isShowDetails) {
    BatchControlRef.value.onHideDetails()
  }
  data.isShowDetails = false
  data.checkedItem = {} as any
  if (show) {
    data.commercialForm = {
      operated_id: -1,
      agent_ids: [],
      game_ids: [],
      column_value: '0',
      column: 'a_rtp_control'
    }
    getSearchList()
  }
}
const OperatorRef = ref<any>()
const resetDetails = () => {
  data.query = {
    page: 1,
    size: 50,
  }
  OperatorRef.value.onHideDetails()
  getSearchList()
}
</script>

<style lang="scss" scoped>
.marginB5 {
  width: 100%;
  padding-bottom: 2px;
  border-bottom: 1px solid #ededed;
}
</style>
